layui.use('form', function() {
    var form = layui.form;

    // 表单验证
    form.verify({
        required: function(value) {
            if (!value) {
                return '该字段为必填项';
            }
        }
    });
});

// 加载学生信息（带分页）
function loadStudents(page = 0, size = 10) {
    $.ajax({
        url: `/students/ajax?page=${page}&size=${size}`,
        method: 'GET',
        success: function(data) {
            renderStudentTable(data.content);  // 渲染学生信息
            renderPagination(data.pageNumber, data.totalPages);  // 渲染分页控件
        },
        error: function() {
            layui.layer.msg('加载数据失败');
        }
    });
}

// 渲染学生信息表格
function renderStudentTable(data) {
    let content = '';
    data.forEach(student => {
        content += `
            <tr>
                <td>${student.id}</td>
                <td>${student.studentNumber}</td>
                <td>${student.name}</td>
                <td>${student.age}</td>
                <td>${student.major}</td>
                <td>
                    <button class="layui-btn layui-btn-xs" onclick="editStudent(${student.id})">编辑</button>
                    <button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteStudent(${student.id})">删除</button>
                </td>
            </tr>
        `;
    });
    $('#student-body').html(content);
}

// 渲染分页控件
function renderPagination(pageNumber, totalPages) {
    const pagination = $('#pagination');
    let content = '';

    // 上一页按钮
    content += `
        <button class="layui-btn layui-btn-xs ${pageNumber === 0 ? 'layui-btn-disabled' : ''}" onclick="loadPage(${pageNumber - 1})">上一页</button>
    `;

    // 页码按钮
    for (let i = 0; i < totalPages; i++) {
        content += `
            <button class="layui-btn layui-btn-xs ${i === pageNumber ? 'layui-btn-disabled' : ''}" onclick="loadPage(${i})">${i + 1}</button>
        `;
    }

    // 下一页按钮
    content += `
        <button class="layui-btn layui-btn-xs ${pageNumber === totalPages - 1 ? 'layui-btn-disabled' : ''}" onclick="loadPage(${pageNumber + 1})">下一页</button>
    `;

    pagination.html(content);
}

// 按页加载数据
function loadPage(page) {
    loadStudents(page, 10);  // 加载指定页的数据
}

// 按姓名查询学生（支持分页）
function searchStudents(page = 0, size = 10) {
    const name = $('#search-name').val();
    if (!name) {
        layui.layer.msg('请输入姓名');
        return;
    }

    $.ajax({
        url: `/students/search?name=${name}&page=${page}&size=${size}`,
        method: 'GET',
        success: function(data) {
            renderStudentTable(data.content);  // 渲染查询结果
            renderPagination(data.pageNumber, data.totalPages);  // 渲染分页控件
        },
        error: function() {
            layui.layer.msg('查询失败');
        }
    });
}

// 绑定查询按钮事件
$('#search-btn').on('click', function() {
    searchStudents(0, 10);  // 初始化为第一页，10条数据
});

// 显示添加学生表单
function addStudent() {
    clearForm();
    openForm('添加学生');
}

// 显示编辑学生表单
function editStudent(id) {
    $.ajax({
        url: `/students/${id}`,
        method: 'GET',
        success: function(data) {
            populateForm(data);
            openForm('编辑学生');
        },
        error: function() {
            layui.layer.msg('加载学生信息失败');
        }
    });
}

// 填充表单数据
function populateForm(data) {
    $('#student-id').val(data.id);
    $('#studentNumber').val(data.studentNumber);
    $('#studentName').val(data.name);
    $('#studentAge').val(data.age);
    $('#studentMajor').val(data.major);
}

// 清空表单
function clearForm() {
    $('#student-id').val('');
    $('#studentNumber').val('');
    $('#studentName').val('');
    $('#studentAge').val('');
    $('#studentMajor').val('');
}

// 打开表单弹窗
function openForm(title) {
    layui.layer.open({
        type: 1,
        title: title,
        content: $('#student-form'),
        area: ['500px', '400px']
    });
}

// 删除学生
function deleteStudent(id) {
    layui.layer.confirm('确认删除该学生吗?', {icon: 3, title: '提示'}, function(index) {
        $.ajax({
            url: `/students/${id}`,
            method: 'DELETE',
            success: function() {
                layui.layer.msg('删除成功');
                loadStudents();  // 刷新学生列表
            },
            error: function() {
                layui.layer.msg('删除失败');
            }
        });
        layui.layer.close(index);
    });
}

// 保存学生信息（添加或编辑）
function saveStudent() {
    const id = $('#student-id').val();
    const studentData = {
        studentNumber: $('#studentNumber').val(),
        name: $('#studentName').val(),
        age: $('#studentAge').val(),
        major: $('#studentMajor').val()
    };

    let url = '/students';
    let method = 'POST';

    if (id) {
        url = `/students/${id}`;
        method = 'PUT';
    }

    $.ajax({
        url: url,
        method: method,
        contentType: 'application/json',
        data: JSON.stringify(studentData),
        success: function() {
            layui.layer.msg('保存成功');
            layui.layer.closeAll();  // 关闭表单弹窗
            loadStudents();  // 刷新学生列表
        },
        error: function() {
            layui.layer.msg('保存失败');
        }
    });
}

// 关闭表单弹窗
function closeForm() {
    layui.layer.closeAll();
}
